package com.nb.filter;

import com.alibaba.fastjson.JSON;
import com.nb.result.BaseContext;
import com.nb.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //资源匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次uri
        String uri = request.getRequestURI();
        //1.定义不需要拦截的路径
        String[] urls = new String[] {
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
                "/user/sendMsg",
                "/user/login"

        };
        //2.判断本次请求是否需要处理
        boolean check = check(urls,uri);
        //3.不需要处理就放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //4.判断登录状态，if 登录---》 则放行
        if (request.getSession().getAttribute("employee") != null) {
            //获取此次用户id
            Long empId = (Long) request.getSession().getAttribute("employee");
            //通过threadlocal进行保存
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }

        //手机端
        if (request.getSession().getAttribute("user") != null) {
            //获取此次用户id
            Long userId = (Long) request.getSession().getAttribute("user");
            //通过threadlocal进行保存
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }
        //5.未登录返回结果信息给前端
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    //判断本次uri是不是需要拦截的请求
    public  boolean check(String[] urls,String requestURI) {
        for (String url : urls) {
            //路径匹配器
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
